package com.tool_stdy.RedisTest;

import java.util.List;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Response;
import redis.clients.jedis.Transaction;

import com.alibaba.fastjson.JSON;
import com.tool_stdy.utils.JedisUtils;

public class JedisTestWatch {

	public static void testLink(String key, String value, int length)
			throws InterruptedException {
		// Long rpush = jedis.rpush(key, value);
		// while (jedis.llen(key) > length) {
		// System.out.println("准备删除..");
		// Thread.sleep(4000);
		// String lpop = jedis.lpop(key);
		// }
		// System.out.println("done");
		Jedis jedis = JedisUtils.getPool().getResource();
		try {
			List<Object> result = null;
			while (result == null || result.isEmpty()) {
				jedis.watch(key);
				Long extItermNum = jedis.llen(key);
				Transaction tx = jedis.multi();
				tx.rpush(key, value);
				while (extItermNum + 1 > length) {
					Response<String> lpop = tx.lpop(key);
					extItermNum--;
				}
				result = tx.exec();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			JedisUtils.getPool().returnResource(jedis);
		}

	}

	public static void testLinkRead(String key) {
		Jedis jedis = JedisUtils.getPool().getResource();
		List<String> lrange = jedis.lrange(key, 0, -1);
		JedisUtils.getPool().returnResource(jedis);
		System.out.println(JSON.toJSONString(lrange));
	}

	public static void main(String[] args) throws InterruptedException {
		// new Thread(new Runnable() {
		// public void run() {
		// try {
		// testLink("test", "buid_" + 23, 5);
		// } catch (InterruptedException e) {
		// e.printStackTrace();
		// }
		// }
		// }).start();
		//
		// new Thread(new Runnable() {
		// public void run() {
		// try {
		// testLink("test", "buid_" +24, 5);
		// } catch (InterruptedException e) {
		// e.printStackTrace();
		// }
		// }
		// }).start();
//		for (int i = 0; i < 1000; i++) {
//			new Thread(new Runnable() {
//				public void run() {
//					try {
//						Thread.sleep(1000);
//						testLink("test1", Thread.currentThread().getName()
//								+ "_buid_" + 5, 5);
//					} catch (InterruptedException e) {
//						e.printStackTrace();
//					}
//				}
//			}).start();
//		}
		for (int i = 0; i < 1000; i++) {
			new Thread(new Runnable() {
				public void run() {
					try {
						testLink("test2", Thread.currentThread().getName()
								+ "_buid_" + 15, 5);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}).start();
		}
		Thread.sleep(10000);
		testLink("test", "buid_" + 16, 5);
		testLinkRead("test");
	}
}
